package AS3.calculator {
import AS3.*;
import AS3.calculator.CoefficientCalculator;
import AS3.CalculationResult;
import AS3.constants.Coefficients;
import AS3.constants.combo.AcDuration;
import AS3.constants.combo.AcFrequency;
import AS3.constants.combo.AcTemp;
import AS3.constants.combo.BathVolume;
import AS3.constants.combo.Clothes;
import AS3.constants.combo.Cooker;
import AS3.constants.combo.ElectricityConsumption;
import AS3.constants.combo.FlightClass;
import AS3.constants.combo.FoodAmount;
import AS3.constants.combo.FoodOrigin;
import AS3.constants.combo.Fridge;
import AS3.constants.combo.FrozenFood;
import AS3.constants.combo.FuelType;
import AS3.constants.combo.FurnitureElectronic;
import AS3.constants.combo.HouseHeating;
import AS3.constants.combo.HouseHeatingSource;
import AS3.constants.combo.HouseInsulation;
import AS3.constants.combo.HouseMaterial;
import AS3.constants.combo.HouseType;
import AS3.constants.combo.HouseVentilation;
import AS3.constants.combo.HouseHeating;
import AS3.constants.combo.MeatConsumption;
import AS3.constants.combo.Packaging;
import AS3.constants.combo.PassengerFrequency;
import AS3.constants.combo.Recreation;
import AS3.constants.combo.Recycling;
import AS3.constants.combo.VehicleAge;
import AS3.constants.combo.VehicleType;
import AS3.Country;
import AS3.Person;

import mx.controls.Alert;

import mx.core.Application;
import mx.core.FlexGlobals;

import zakladki.AS3.VehicleSelectedData;
import zakladki.alert;

public class BookmarkCalculator {

    private var coefficientCalculator:CoefficientCalculator;

    private var refData:ReferenceTemperatures = new ReferenceTemperatures();

    public function calculate(chosenCountry:Country, person:Person,params:CalculationParams):CalculationResult {
        var calculationResult:CalculationResult = new CalculationResult();

        calculationResult = calculateHome(calculationResult, person, chosenCountry,params);
        calculationResult = calculateHotWater(calculationResult,chosenCountry,person,params);
        calculationResult = calculateFood(calculationResult, person,params);
        calculationResult = calculateConsumption(calculationResult, person, chosenCountry,params);
        calculationResult = calculateElectricity(calculationResult, person,params);
        calculationResult = calculateTransport(calculationResult, person, chosenCountry,params);

        return calculationResult;
    }


    private function calculateTransport(calcResult:CalculationResult,person:Person, chosenCountry:Country,params:CalculationParams):CalculationResult {
        calcResult = calcPrivateTransport(calcResult,person,chosenCountry,params);
        return calcPublicTransport(calcResult,person,chosenCountry,params);
    }

    private function calcPrivateTransport(calcResult:CalculationResult, osoba:Person,chosenCountry:Country,params:CalculationParams):CalculationResult {
        var RX:Number, FCl100:Number, CarSize:Number, CoolingIntensityRef:Number, ECEff:Number;
        var passenger:Number = new Number(1);
        var j:int;

        var vehicleType:int;
        var fuelType:int;
        var vehicleAge:int;
        var passengerFreq:int;
        var acEnabled:Boolean;
        var fuelConsumption:int;
        var distancePerWeek:int;


        var vehicleArrays:Array = osoba.getVehicleDataArray();

        var fuelBurningEmission:Number = new Number(0);
        var carProductionEmission:Number = new Number(0);

        for each (var vehicleData:VehicleSelectedData in vehicleArrays) {

            vehicleType = vehicleData.vehicleType;
            vehicleAge = vehicleData.age;
            fuelConsumption = vehicleData.fuelConsumption;
            fuelType = vehicleData.fuelType;
            distancePerWeek = vehicleData.distancePerWeek;
            passengerFreq = vehicleData.passengerFreq;
            acEnabled = vehicleData.acEnabled;

            if (vehicleType != VehicleType.NONE) {
                var oilGJConsumptionPrimary:Number = 0;
                var gasGJConsumptionPrimary:Number = 0;
                var electricityGJConsumptionPrimary:Number = 0;

                var oilGJConstructionPrimary:Number = 0;
                var coalGJConstructionPrimary:Number = 0;
                var gasGJConstructionPrimary:Number = 0;
                var electricityConstructionGJPrimary:Number = 0;

                if (vehicleType != VehicleType.BIKE) {
                    if (params.units == 'M') {
                        FCl100 = fuelConsumption
                    }
                    else {
                        FCl100 = 235.2145 / fuelConsumption;  // 1mpg=235.2145 l/100km
                    }
                    FCl100 = FCl100 / 8.0;

                    switch (fuelType) {
                        case FuelType.PETROL: RX = 0.180 * FCl100;RX = RX / 0.83;
                            oilGJConsumptionPrimary += 0.042 * fuelConsumption * distancePerWeek/(100*7) * 365 * 1.4;
                            break;// Petroleum refining and distribution efficiency = 0.830 Station-to-wheel -> Well-to-wheel
                        case FuelType.DIESEL: RX = 0.200 * FCl100;RX = RX / 0.83;
                            oilGJConsumptionPrimary += 0.042 * fuelConsumption * distancePerWeek/(100*7) * 365;
                            break;// Petroleum refining and distribution efficiency = 0.830 Station-to-wheel -> Well-to-wheel
                        case FuelType.CNG: RX = 0.112 * FCl100;RX = RX / 0.83;
                            gasGJConsumptionPrimary += 0.049 * fuelConsumption * distancePerWeek/(100*7) * 365;
                            break;// Petroleum refining and distribution efficiency = 0.830 Station-to-wheel -> Well-to-wheel
                        case FuelType.ELECTRIC:
                        {
                            //RX = 0.2 * 0.45 * coefficientCalculator.getCOCoeffElectrGJ() / coefficientCalculator.getGasElectrGJ();
                            RX = 0.2 * 0.45 * params.electricityGJCO2Coefficient / Coefficients.GAS_ELECTRICITY_GJ;
                            electricityGJConsumptionPrimary += distancePerWeek/7 * 365 * 0.23 * 3.6; //=> MJ
                            electricityGJConsumptionPrimary = electricityGJConsumptionPrimary/1000; //GJ
                            switch (vehicleType) {
                                case VehicleType.SMALL_ENGINE: RX = RX * 0.8; break;
                                case VehicleType.MEDIUM: RX = RX * 1.2; break;
                                case VehicleType.BIG: RX = RX * 1.8; break;
                                case VehicleType.LARGE: RX = RX * 2.9; break;
                            }
                            break;
                        }
                    }
                    // http://www.paulchefurka.ca/Electric%20Cars%20and%20CO2.html
                    // Honda's hydrogen fuel cell car requires 0.48kWh/km (http://www.thewatt.com/article-1162-nested-1-0.html),
                    // battery vehciles existing today (not using Li-ion batteries), require around 0.23kWh/km
                    // the new Tesla using Li-ion uses just 0.125 kWh/km.

                    if (acEnabled) {
                        var coolingIntensity:Number = 1;
                        CoolingIntensityRef = 1;
                        for (j = 0; j < 12; j++) {
                            //  CoolingIntensity=CoolingIntensity+CoolingS[T[j]];
                            //  CoolingIntensityRef=CoolingIntensityRef+CoolingS[THRef[j]];
                        }
                        ECEff = coolingIntensity / CoolingIntensityRef;
                        RX = RX + 0.0020 * ECEff;
                    }

                    RX = RX / 1000;

                    if (params.units == 'M') {
                        RX = RX * distancePerWeek
                    }

                    RX = RX * 52;

                    //if cbCarSharnig == 0 then OsobaTowarzyszaca=1.0;
                    switch (passengerFreq) {
                        case PassengerFrequency.SPORADICALLY: passenger = 1.25;break;
                        case PassengerFrequency.SOMETIMES: passenger = 1.5;break;
                        case PassengerFrequency.USUALLY: passenger = 1.75;break;
                        case PassengerFrequency.ALMOST_ALWAYS: passenger = 2.0;break;
                    }

                    RX = RX / passenger;
                    fuelBurningEmission = fuelBurningEmission + RX;
                }

                if (vehicleAge == VehicleAge.NOT_OLDER_THAN_15) {
                    RX = 1;
                } else {
                    RX = 0.05;
                }

                var constructionEnergy:Number = 113.6;


                CarSize = 0.04; // Rower, większa masa, ale statystycznie więcej aluminium

                switch (vehicleType) {
                    case VehicleType.BIKE: CarSize = 0.2; break;
                    case VehicleType.SMALL_ENGINE: CarSize = 0.8; break;
                    case VehicleType.MEDIUM: CarSize = 1.2; break;
                    case VehicleType.BIG: CarSize = 1.8; break;
                    case VehicleType.LARGE: CarSize = 2.9; break;
                }

                constructionEnergy = constructionEnergy * CarSize/1.2;
                oilGJConstructionPrimary += constructionEnergy * 0.36;
                gasGJConstructionPrimary += constructionEnergy * 0.1;
                electricityConstructionGJPrimary += constructionEnergy * 0.33;
                coalGJConstructionPrimary += constructionEnergy * 0.21;

                //      CarSize=CarSize*17.5;
                //CarSize = CarSize * (osoba.transportEmissionReduction + 10 * osoba.industrialEmissionReduction + 3.3 * coefficientCalculator.getCOCoeffElectrGJ() / coefficientCalculator.getGasElectrGJ());
                CarSize = CarSize * (osoba.transportEmissionReduction + 10 * osoba.industrialEmissionReduction + 3.3 * params.electricityGJCO2Coefficient / Coefficients.GAS_ELECTRICITY_GJ);
                // Przeliczenie ton samochodu -> tony CO2, surowce, montaż, serwisowanie

                RX = RX * CarSize / passenger / 15; // Przeciętny samochód przejeżdża rocznie 16000 km, rozłożenie emisji 5 ton (+korekta rozmiar) czas życia 15 lat

                if (acEnabled) {
                    switch (vehicleType) {
                        case VehicleType.SMALL_ENGINE: RX = RX + 1.1 / 12; break;
                        case VehicleType.MEDIUM: RX = RX + 1.3 / 12; break;
                        case VehicleType.BIG: RX = RX + 1.5 / 12; break;
                        case VehicleType.LARGE: RX = RX + 1.7 / 12; break;
                    }
                }

                carProductionEmission = carProductionEmission + RX;
                if (!params.nonStatisticMode) // w trybie statystycznym dla ludności
                {
                    fuelBurningEmission = fuelBurningEmission / chosenCountry.carPer1000 / 10000 / 100;
                    carProductionEmission = carProductionEmission / chosenCountry.carPer1000 / 1000 * passenger;
                }

                calcResult.fuelBurningsEnergy.oilEnergy += oilGJConsumptionPrimary;
                calcResult.fuelBurningsEnergy.gasEnergy += gasGJConsumptionPrimary;
                calcResult.fuelBurningsEnergy.electricityEnergy += electricityGJConsumptionPrimary;

                calcResult.carProductionEnergy.coalEnergy += coalGJConstructionPrimary;
                calcResult.carProductionEnergy.oilEnergy += oilGJConstructionPrimary;
                calcResult.carProductionEnergy.gasEnergy += gasGJConstructionPrimary;
                calcResult.carProductionEnergy.electricityEnergy += electricityConstructionGJPrimary;

                calcResult.coalEnergy += coalGJConstructionPrimary;
                calcResult.oilEnergy += (oilGJConsumptionPrimary + oilGJConstructionPrimary);
                calcResult.gasEnergy += (gasGJConsumptionPrimary + gasGJConstructionPrimary);
                calcResult.electricityEnergy += (electricityGJConsumptionPrimary + electricityConstructionGJPrimary);
            }
        }


        calcResult.fuelBurnings = fuelBurningEmission;
        calcResult.carProduction = carProductionEmission;

        return calcResult;
    }

    private function calcPublicTransport(calcResult:CalculationResult,osoba:Person, chosenCountry:Country,params:CalculationParams):CalculationResult {
        var RX:Number = new Number(0);
        var emissionCO2:Number = new Number(0);
        var pubTrEmission:Number;
        var airEmission:Number;

        var oilGJConsumptionPrimary:Number = 0;
        var gasGJConsumptionPrimary:Number = 0;
        var electricityGJConsumptionPrimary:Number = 0;

        var oilGJConstructionPrimary:Number = 0;
        var coalGJConstructionPrimary:Number = 0;
        var gasGJConstructionPrimary:Number = 0;
        var electricityConstructionGJPrimary:Number = 0;

        var constructionEnergy:Number = 0;

        // a.miejski, a.dalekob. mikrob, tramwaj, poc.podm., poc.dalekob.
//  Calculate na koniec (przełączenie trybu) i wyliczenie i info
        pubTrEmission = osoba.cityBus * 52 * 0.040 +
                osoba.longDistanceBus * 52 * 0.060 +
                osoba.miniBus * 52 * 0.100 +
                osoba.tramSubway * 52 * 0.025 * params.electricityGJCO2Coefficient / Coefficients.GAS_ELECTRICITY_GJ + // uwzględnienie pochodzenia energii: Subway
                osoba.suburbanTrain * 52 * 0.028 * params.electricityGJCO2Coefficient / Coefficients.GAS_ELECTRICITY_GJ  + // uwzględnienie pochodzenia energii: Podmiejski
                osoba.longDistanceTrain * 52 * 0.036 * params.electricityGJCO2Coefficient / Coefficients.GAS_ELECTRICITY_GJ  + // uwzględnienie pochodzenia energii: Dalekobieżny
                osoba.taxi * 52 * 0.260; // Taxi 8l benzyna, korekta 0.83, 1.25 osoby

        //Rose 0.72MJ /passenger km  w odniesieniu do cityBus
        //
        var cityBusEmbodiedEnergyMJ:Number = 0.022;
        oilGJConsumptionPrimary += (osoba.cityBus * 52 * 0.72  +
                                    osoba.longDistanceBus * 52 * 0.72 * 1.5 +
                                    osoba.miniBus * 52 * 0.72 * 4)/1000;

        constructionEnergy += (cityBusEmbodiedEnergyMJ * osoba.cityBus * 52 +
                               cityBusEmbodiedEnergyMJ * osoba.longDistanceBus * 52 +
                               cityBusEmbodiedEnergyMJ * osoba.miniBus * 52 * 0.18 //2 tony vs 11 ton
                              )/1000;

        constructionEnergy += (osoba.longDistanceTrain * 52 * 0.27 +
                                             osoba.suburbanTrain * 52 * 0.27)/1000;

        //0.27 MJ per passenger_km for trains => consumption and construction

        electricityGJConsumptionPrimary += (osoba.tramSubway * 52 * 0.4 + 52 * 0.27 * (osoba.longDistanceTrain + osoba.suburbanTrain))/1000;

        oilGJConsumptionPrimary += (2.2 * osoba.taxi * 52)/1000;
        constructionEnergy += (0.65 * osoba.taxi * 52)/1000;

        calcResult.publicTransportEnergy.oilEnergy += oilGJConsumptionPrimary;
        calcResult.publicTransportEnergy.electricityEnergy += electricityGJConsumptionPrimary;

        calcResult.publicTransportEnergy.oilEnergy += constructionEnergy * 0.36;
        calcResult.publicTransportEnergy.gasEnergy += constructionEnergy * 0.1;
        calcResult.publicTransportEnergy.electricityEnergy += constructionEnergy * 0.33;
        calcResult.publicTransportEnergy.coalEnergy += constructionEnergy * 0.21;




        pubTrEmission = pubTrEmission / 1000; // kg->tony
        if (params.units != 'M') {
        }//RX=ConvertMiles2Km(RX); }

        // w biednych krajach autobusy i pociągi są wypełnione nawet x4 względem Polski, w bogatych jeżdżą prawie puste
        if (chosenCountry.consumption2000 <= 10000) {
            pubTrEmission = pubTrEmission * Math.sqrt(chosenCountry.consumption2000 / 5000);
        }
        else {
            pubTrEmission = pubTrEmission * Math.sqrt(10000 / 5000);
        }

        if (!params.nonStatisticMode) {
            pubTrEmission = pubTrEmission / 100;          // w trybie statystycznym dla ludności
        }

//11. Ile godzin rocznie spędzasz latając samolotem?
//  wpływ całkowity 0.450 kg/km (Fuel: 0.35) - długie, 0.730 kg/km (Fuel: 0.46) - krótkie
//  Prędkość długie - 800 km/h, krótkie - 500 km/h z uwzgl startu i ląd wolniej
//  Emisja kg CO2/h 0.344 - długie, 0.365 - krótkie
//  Ale duże odrzutowce na granicy tropopauzy NO, cirrus, ozon
//  Więc koniec końców odwrotnie
//  RX=0.34*I_eFlightLong+0.40*I_eFlightShort; - właściwa
//  wpływ całkowity 0.450 kg/km (Fuel: 0.35, Prod&Maint 0.10) - długie, 0.730 kg/km (Fuel: 0.46, Prod&Maint 0.27) - krótkie
//  Prędkość długie - 800 km/h, krótkie - 500 km/h z uwzgl startu i ląd wolniej
//  Emisja kg CO2/h 0.36 (Fuel: 0.28, Prod&Maint 0.08) - długie, 0.37 (Fuel: 0.23, Prod&Maint 0.14) - krótkie
//  Pomijamy inne GHG (czynnik paliwa 2-4: weźmy 2,3 razem:
//  Emisja kg CO2/h 0.20 (Fuel: 0.12, Prod&Maint 0.08) - długie, 0.24 (Fuel: 0.1, Prod&Maint 0.14) - krótkie
//  RX=0.34*I_eFlightLong+0.40*I_eFlightShort; - właściwa


        var shortDistanceKm:Number = 500 * osoba.shortDistanceFlights;
        var longDistanceKm:Number = 800 * osoba.longDistanceFlights;

        var aircraftOilGJPrimary:Number = 0;

        aircraftOilGJPrimary += shortDistanceKm * 1.7 + longDistanceKm * 1.28; //MJ
        //kerozyna 46MJ/kg
        aircraftOilGJPrimary += aircraftOilGJPrimary/1000 * Coefficients.OIL_KG_PER_GJ_HEAT/46; //GJ

        //Rose
        var airCraftConstructionEnergy:Number = (0.195 * shortDistanceKm + 0.19 * longDistanceKm) /1000;

        calcResult.airTransportEnergy.oilEnergy += aircraftOilGJPrimary;
        calcResult.airConditioningEnergy.oilEnergy += airCraftConstructionEnergy * 0.36;
        calcResult.airConditioningEnergy.gasEnergy += airCraftConstructionEnergy * 0.1;
        calcResult.airConditioningEnergy.electricityEnergy += airCraftConstructionEnergy * 0.33;
        calcResult.airConditioningEnergy.coalEnergy += airCraftConstructionEnergy * 0.21;



        constructionEnergy += (0.195 * shortDistanceKm + 0.19 * longDistanceKm) /1000;

        //współczynniki z Excela Marcina
        oilGJConstructionPrimary += constructionEnergy * 0.36;
        gasGJConstructionPrimary += constructionEnergy * 0.1;
        electricityConstructionGJPrimary += constructionEnergy * 0.33;
        coalGJConstructionPrimary += constructionEnergy * 0.21;


        airEmission = (0.12 * (osoba.transportEmissionReduction + 1) / 2 + 0.08 * osoba.industrialEmissionReduction) * osoba.longDistanceFlights
                + (0.10 * (osoba.transportEmissionReduction + 1) / 2 + 0.14 * osoba.industrialEmissionReduction) * osoba.shortDistanceFlights;
        // samo CO2 i produkcja
        if (osoba.flightClass == FlightClass.BUSINESS) {
            aircraftOilGJPrimary = aircraftOilGJPrimary * 2;
            airEmission = airEmission * 2.0;
        }
        else if (osoba.flightClass == FlightClass.FIRST) {
            aircraftOilGJPrimary = aircraftOilGJPrimary * 3;
            airEmission = airEmission * 3.0;
        }

        oilGJConsumptionPrimary += aircraftOilGJPrimary;

        // w trybie statystycznym dla ludności
        if (!params.nonStatisticMode) {
            airEmission = airEmission / 100;
        }

        calcResult.publicTransport = pubTrEmission;
        calcResult.airTransport = airEmission;

        calcResult.coalEnergy += coalGJConstructionPrimary;
        calcResult.oilEnergy += (oilGJConsumptionPrimary + oilGJConstructionPrimary);
        calcResult.gasEnergy += (gasGJConsumptionPrimary + gasGJConstructionPrimary);
        calcResult.electricityEnergy += (electricityGJConsumptionPrimary + electricityConstructionGJPrimary);

        return calcResult;
    }

    /***************************************************************************************
     Jak sama nazwa wskazuje - przelicza mile na kilometry
     ***************************************************************************************/

    private function ConvertMiles2Km(X:Number):Number {
        return 1.609344 * X;
    }

    /******************************   Konsumpcja   ****************************************/

    private function calculateConsumption(calcResult:CalculationResult,person:Person, chosenCountry:Country,params:CalculationParams):CalculationResult {
        var areaSqMeters:Number;
        var personNumbers:Number;
        var result:Number;

        result = 0.0;

        areaSqMeters = person.livingArea;
        if (params.units != 'M') {
            areaSqMeters = areaSqMeters * 0.09290304; // Przeliczenie ze stóp na metry (kwadratowe 0.3048*0.3048)
        }
        personNumbers = person.personNumber;

        switch (person.clothes) {
            case Clothes.SECOND_HAND:
                result = 0.15;
                break;
            case Clothes.NEW_WHEN_WORN_OUT:
                result = 0.30;
                break;
            case Clothes.ALWAYS_NEW:
                result = 0.50;
                break;
        }

        switch (person.packaging) {
            case Packaging.MINIMAL:
                result = result + 0.30;
                break;
            case Packaging.ALL:
                result = result + 0.40;
                break;
            case Packaging.FANCY:
                result = result + 0.55;
                break;
        }

        switch (person.furnitureElectronics) {
            case FurnitureElectronic.SECOND_HAND:
                result = result + (0.20 + 0.15 * areaSqMeters / 30 / personNumbers);
                break;
            case FurnitureElectronic.USUALLY_NEW:
                result = result + (0.35 + 0.35 * areaSqMeters / 30 / personNumbers);
                break;
            case FurnitureElectronic.FASHIONABLE:
                result = result + (0.70 + 0.70 * areaSqMeters / 30 / personNumbers);
                break;// I enjoy having the latest technology and home fashion
        }

        switch (person.recycling) {
            case Recycling.NO_RECYCLING:
                result = result * 1.00;
                break;
            case Recycling.SMALL_PART:
                result = result * 0.97;
                break;
            case Recycling.FAIR_PART:
                result = result * 0.90;
                break;
            case Recycling.LARGE_PART:
                result = result * 0.80;
                break;
        }

        switch (person.recreation) {
            case Recreation.OUTDOOR:
                result = result + 0.15;
                break;
            case Recreation.CINEMAS_PUBS:
                result = result + 0.35;
                break;
            case Recreation.TECHNICAL:
                result = result + 0.7;
                break;
        }

        var energyConsGJ:Number = result * 6.6 ; //kWh;
        energyConsGJ = (energyConsGJ * 3.6/1000) * params.consumptionCoefficient;

        calcResult.personalConsumptionEnergy.electricityEnergy += 0.35 * energyConsGJ;
        calcResult.personalConsumptionEnergy.oilEnergy += 0.4 * energyConsGJ;
        calcResult.personalConsumptionEnergy.coalEnergy += 0.2 * energyConsGJ;
        calcResult.personalConsumptionEnergy.gasEnergy += 0.05 * energyConsGJ;

        var generalRatio:Number = 0.85 * params.consumptionCoefficient/coefficientCalculator.consLevel2CO2(chosenCountry.consumption2000, 1);

        calcResult.generalEnergy.electricityEnergy += generalRatio * 0.35 * energyConsGJ;
        calcResult.generalEnergy.oilEnergy += generalRatio * 0.4 * energyConsGJ;
        calcResult.generalEnergy.coalEnergy += generalRatio * 0.2 * energyConsGJ;
        calcResult.generalEnergy.gasEnergy += generalRatio * 0.05 * energyConsGJ;


        result = result * 1.05 * params.consumptionCoefficient * (0.15 * person.transportEmissionReduction + 0.35 * person.industrialEmissionReduction + 0.5 * params.electricityGJCO2Coefficient / Coefficients.GAS_ELECTRICITY_GJ);
        var generalEmission:Number = 1.7 * coefficientCalculator.consLevel2CO2(chosenCountry.consumption2000, 1); // 1.3 1.9
        generalEmission = generalEmission * (0.2 * person.transportEmissionReduction + 0.4 * person.industrialEmissionReduction + 0.4 * params.electricityGJCO2Coefficient / Coefficients.GAS_ELECTRICITY_GJ);

        calcResult.consumption = result;
        calcResult.general = generalEmission;

        return calcResult;
    }

    /****************************Jedzenie**************************************************/



    private function calculateFood(calcResult:CalculationResult, person:Person,params:CalculationParams):CalculationResult {
        var result:Number,electricityConsumption:Number;

        if ((person.income != -1) && (person.foodAmount != -1)
                && (person.meatConsumption != -1) && (person.foodOrigin != -1)
                && (person.frozenFood != -1)) {
            result = 0.0;
            var personNumber:int = person.personNumber;
            var foodAmount:int = person.foodAmount;
            var meatConsumption:int = person.meatConsumption;
            var foodOrigin:int = person.foodOrigin;
            var frozenFood:int = person.frozenFood;

            switch (foodAmount) {
                case FoodAmount.VERY_LITTLE: result = 1.50;
                    break;
                case FoodAmount.RATHER_LITTLE: result = 1.90;
                    break;
                case FoodAmount.AVERAGE: result = 2.25;
                    break;
                case FoodAmount.RATHER_A_LOT: result = 2.65;
                    break;
                case FoodAmount.A_LOT: result = 3.00;
                    break;
            }

            switch (person.packaging) {
                case Packaging.MINIMAL: result = result * 0.9;
                    break;
                case Packaging.FANCY: result = result * 1.1;
                    break;
            }

            // Wsp�czynnik mi�sa i transportu
            if ((meatConsumption == MeatConsumption.EVERY_DAY) && (foodOrigin == FoodOrigin.EXOTIC)) {
                result = result * 2.82 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.EVERY_DAY) && (foodOrigin == FoodOrigin.ALL)) {
                result = result * 2.17 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.EVERY_DAY) && (foodOrigin == FoodOrigin.LOCAL_AND_SEASONAL)) {
                result = result * 1.50 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.EVERY_DAY) && (foodOrigin == FoodOrigin.LOCAL_SHOP)) {
                result = result * 0.90 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.EVERY_DAY) && (foodOrigin == FoodOrigin.HOME_GROWN)) {
                result = result * 0.50 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.OFTEN) && (foodOrigin == FoodOrigin.EXOTIC)) {
                result = result * 2.49 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.OFTEN) && (foodOrigin == FoodOrigin.ALL)) {
                result = result * 1.92 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.OFTEN) && (foodOrigin == FoodOrigin.LOCAL_AND_SEASONAL)) {
                result = result * 1.35 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.OFTEN) && (foodOrigin == FoodOrigin.LOCAL_SHOP)) {
                result = result * 0.85 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.OFTEN) && (foodOrigin == FoodOrigin.HOME_GROWN)) {
                result = result * 0.45 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.TWICE_A_WEEK) && (foodOrigin == FoodOrigin.EXOTIC)) {
                result = result * 2.17 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.TWICE_A_WEEK) && (foodOrigin == FoodOrigin.ALL)) {
                result = result * 1.67 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.TWICE_A_WEEK) && (foodOrigin == FoodOrigin.LOCAL_AND_SEASONAL)) {
                result = result * 1.17 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.TWICE_A_WEEK) && (foodOrigin == FoodOrigin.LOCAL_SHOP)) {
                result = result * 0.75 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.TWICE_A_WEEK) && (foodOrigin == FoodOrigin.HOME_GROWN)) {
                result = result * 0.39 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.VEGETARIAN) &&   (foodOrigin == FoodOrigin.EXOTIC)) {
                result = result * 1.74 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.VEGETARIAN) && (foodOrigin == FoodOrigin.ALL)) {
                result = result * 1.34 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.VEGETARIAN) && (foodOrigin == FoodOrigin.LOCAL_AND_SEASONAL)) {
                result = result * 0.94 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.VEGETARIAN) && (foodOrigin == FoodOrigin.LOCAL_SHOP)) {
                result = result * 0.60 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.VEGETARIAN) && (foodOrigin == FoodOrigin.HOME_GROWN)) {
                result = result * 0.31 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.VEGAN) && (foodOrigin == FoodOrigin.EXOTIC)) {
                result = result * 1.09 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.VEGAN) && (foodOrigin == FoodOrigin.ALL)) {
                result = result * 0.84 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.VEGAN) && (foodOrigin == FoodOrigin.LOCAL_AND_SEASONAL)) {
                result = result * 0.59 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.VEGAN) && (foodOrigin == FoodOrigin.LOCAL_SHOP)) {
                result = result * 0.40 / 2.82;
            }
            if ((meatConsumption == MeatConsumption.VEGAN) && (foodOrigin == FoodOrigin.HOME_GROWN)) {
                result = result * 0.20 / 2.82;
            }

            // Mro�onki - trzeba wiele energii, �eby przetrzyma� przez p�roku...
            switch (person.frozenFood) {
                case FrozenFood.NEVER: result = result * 0.90; break;
                case FrozenFood.RARELY: result = result * 0.92; break;
                case FrozenFood.ONCE_A_WEEK: result = result * 0.94; break;
                case FrozenFood.OFTEN: result = result * 0.97; break;
                case FrozenFood.EVERY_DAY: result = result * 1.000; break;
            }

            switch (person.recycling) {
                case Recycling.NO_RECYCLING: result = result * 0.95; break;
                case Recycling.LARGE_PART: result = result * 0.90; break;
            }

            electricityConsumption = 0.0;

            if(personNumber != 0){
                switch(person.cookerType){
                    case Cooker.ELECTRIC:
                        electricityConsumption = electricityConsumption + 77.0/(1 + (2/personNumber));
                        break;
                    case Cooker.INDUCTIVE:
                        electricityConsumption = electricityConsumption + 62.0/(1 + (2/personNumber));
                        break;
                }
            }

            if (personNumber == 1) {
                switch (person.fridgeType) {
                    case Fridge.LOW_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 600; break;//DG
                    case Fridge.MEDIUM_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 400; break;//CB
                    case Fridge.CLASS_A_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 285; break;//A
                    case Fridge.VERY_HIGH_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 230; break;//A+
                }
                if (person.separateFridge) {
                    electricityConsumption = electricityConsumption + 305;
                }
            }
            if (personNumber == 2) {
                switch (person.fridgeType) {
                    case Fridge.LOW_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 660 / personNumber; break;//DG
                    case Fridge.MEDIUM_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 440 / personNumber; break;//CB
                    case Fridge.CLASS_A_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 310 / personNumber; break;//A
                    case Fridge.VERY_HIGH_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 250 / personNumber; break;//A+
                }
                if (person.separateFridge) {
                    electricityConsumption = electricityConsumption + 350 / 2;
                }
            }
            if (personNumber == 3) {
                switch (person.fridgeType) {
                    case Fridge.LOW_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 700 / personNumber; break;//DG
                    case Fridge.MEDIUM_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 470 / personNumber; break;//CB
                    case Fridge.CLASS_A_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 330 / personNumber; break;//A
                    case Fridge.VERY_HIGH_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 268 / personNumber; break;//A+
                }
                if (person.separateFridge) {
                    electricityConsumption = electricityConsumption + 415 / 3;
                }
            }
            if (personNumber == 4) {
                switch (person.fridgeType) {
                    case Fridge.LOW_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 740 / personNumber; break;//DG
                    case Fridge.MEDIUM_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 500 / personNumber; break;//CB
                    case Fridge.CLASS_A_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 350 / personNumber; break;//A
                    case Fridge.VERY_HIGH_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 285 / personNumber; break;//A+
                }
                if (person.separateFridge) {
                    electricityConsumption = electricityConsumption + 420 / 4;
                }
            }
            if (personNumber > 4) {
                switch (person.fridgeType) {
                    case Fridge.LOW_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 185; break;//DG
                    case Fridge.MEDIUM_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 125; break;//CB
                    case Fridge.CLASS_A_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 85; break;//A
                    case Fridge.VERY_HIGH_EFFICIENCY: electricityConsumption =
                            electricityConsumption + 70; break;//A+
                }
                if (person.separateFridge) {
                    electricityConsumption = electricityConsumption + 105;
                }
            }

            electricityConsumption = electricityConsumption * (0.15 + 0.85 *
                    (100.0 - person.renewableRatio) / 100.0);
            electricityConsumption = electricityConsumption / 1000.0; //

            electricityConsumption = 3.6 * electricityConsumption; // MWh->GJ
            var energyGJConsumption:Number = electricityConsumption; //GJ

            electricityConsumption = electricityConsumption / 1000.0; // kg

            electricityConsumption = electricityConsumption *
                    params.electricityGJCO2Coefficient; // GJ -> Tone CO2

            switch (person.electricity) {
                case ElectricityConsumption.SAVING:
                    electricityConsumption = electricityConsumption * 0.8;
                    energyGJConsumption = energyGJConsumption * 0.8;
                    break;
                case ElectricityConsumption.NO_REDUCTION:
                    electricityConsumption = electricityConsumption * 1.3;
                    energyGJConsumption = energyGJConsumption * 1.3;
                    break;
            }

            var foodTypeEnergyGJ:Number = result /0.095; //0.095 tony CO2 per MJ Rose

            result = result + electricityConsumption;

            calcResult.foodEnergy.oilEnergy += 0.9 * foodTypeEnergyGJ;
            calcResult.foodEnergy.electricityEnergy += 0.1 * foodTypeEnergyGJ;
            calcResult.foodEnergy.electricityEnergy += energyGJConsumption;

            calcResult.oilEnergy += 0.9 * result;
            calcResult.electricityEnergy += 0.1 * result;

            result = result * params.consumptionCoefficient * (0.1 + 0.2 *
                    person.transportEmissionReduction + 0.3 * person.industrialEmissionReduction +
                    0.4 * params.electricityGJCO2Coefficient / Coefficients.GAS_ELECTRICITY_GJ);

            calcResult.food = result;

        }
        return calcResult;
    }

    private function calculateElectricity(calcResult:CalculationResult,person:Person,params:CalculationParams):CalculationResult {
        var result:Number;

        result = getElectricityYearMWh(person);

        calcResult.directElectricity.electricityEnergy = result * (0.15 + 0.85 * (100 - person.renewableRatio)/100)*3.6;


        result = result * params.electricityMWhCO2Coefficient; // MWh -> Tone CO2
        result = result / 1000.0; // kg CO2->Tony CO2
        result = result * (0.15 + 0.85 * (100.0 - person.renewableRatio) / 100.0);

        calcResult.electricity = result;

        return calcResult;
    }

    private function getElectricityYearMWh(osoba:Person):Number {
        var result:Number,personNumbers:Number;

        result = 0.0;
        personNumbers = osoba.personNumber;
        switch (personNumbers) {
            case 1:{
                if (osoba.lighting) {
                    result = result + 225;
                } // oświetlenie + drobny AGD
                if (osoba.washingMachineSelected) {
                    result = result + 70;
                }
                if (osoba.underwearDryer) {
                    result = result + 125;
                }
                if (osoba.tv) {
                    result = result + 150;
                }
                if (osoba.videoDVD) {
                    result = result + 75;
                }
                if (osoba.cableTV) {
                    result = result + 75;
                }
                if (osoba.computer) {
                    result = result + 80;
                }
                if (osoba.radioHiFi) {
                    result = result + 70;
                }
                break;
            }
            case 2:{
                if (osoba.lighting) {
                    result = result + 150;
                } // oświetlenie + drobny AGD
                if (osoba.washingMachineSelected) {
                    result = result + 66;
                }
                if (osoba.underwearDryer) {
                    result = result + 112;
                }
                if (osoba.tv) {
                    result = result + 100;
                }
                if (osoba.videoDVD) {
                    result = result + 50;
                }
                if (osoba.cableTV) {
                    result = result + 50;
                }
                if (osoba.computer) {
                    result = result + 70;
                }
                if (osoba.radioHiFi) {
                    result = result + 45;
                }
                break;
            }
            case 3:{
                if (osoba.lighting) {
                    result = result + 120;
                } // oświetlenie + drobny AGD
                if (osoba.washingMachineSelected) {
                    result = result + 66;
                }
                if (osoba.underwearDryer) {
                    result = result + 108;
                }
                if (osoba.tv) {
                    result = result + 80;
                }
                if (osoba.videoDVD) {
                    result = result + 40;
                }
                if (osoba.cableTV) {
                    result = result + 40;
                }
                if (osoba.computer) {
                    result = result + 60;
                }
                if (osoba.radioHiFi) {
                    result = result + 37;
                }
                break;
            }
            case 4:{
                if (osoba.lighting) {
                    result = result + 90;
                } // oświetlenie + drobny AGD
                if (osoba.washingMachineSelected) {
                    result = result + 66;
                }
                if (osoba.underwearDryer) {
                    result = result + 105;
                }
                if (osoba.tv) {
                    result = result + 65;
                }
                if (osoba.videoDVD) {
                    result = result + 32;
                }
                if (osoba.cableTV) {
                    result = result + 32;
                }
                if (osoba.computer) {
                    result = result + 50;
                }
                if (osoba.radioHiFi) {
                    result = result + 31;
                }
                break;
            }
            default:{
                if (osoba.lighting) {
                    result = result + 60;
                } // oświetlenie + drobny AGD
                if (osoba.washingMachineSelected) {
                    result = result + 65;
                }
                if (osoba.underwearDryer) {
                    result = result + 100;
                }
                if (osoba.tv) {
                    result = result + 60;
                }
                if (osoba.videoDVD) {
                    result = result + 30;
                }
                if (osoba.cableTV) {
                    result = result + 30;
                }
                if (osoba.computer) {
                    result = result + 50;
                }
                if (osoba.radioHiFi) {
                    result = result + 30;
                }
                break;
            }
        }
        result = result * 1.5;
        result = result / 1000.0; // kWh->MWh
        switch (osoba.electricity) {
            case ElectricityConsumption.SAVING:
                result = result * 0.7;
                break;
            case ElectricityConsumption.NO_REDUCTION:
                result = result * 1.5;
                break;
        }

        return result;
    }

    /******************************Ciepła woda *******************************************/

    private function calculateHotWater(calcResult:CalculationResult,chosenCountry:Country,person:Person,params:CalculationParams):CalculationResult {

        var RE:Number = 0;
        var RX:Number = 0;
        var EW:Number = 0;

        if (person.bathNumber >= 0) {
            if (params.units == "M") {
                switch (person.waterBathVolume) {
                    case BathVolume.LITERS_50:  RX = 50.0;break;
                    case BathVolume.LITERS_100: RX = 100.0;break;
                    case BathVolume.LITERS_150: RX = 150.0;break;
                    case BathVolume.LITERS_200: RX = 200.0;break;
                    case BathVolume.LITERS_250: RX = 250.0;break;
                    case BathVolume.LITERS_300: RX = 300.0;break;
                    case BathVolume.LITERS_350: RX = 350.0;break;
                    case BathVolume.LITERS_400: RX = 400.0;break;
                    case BathVolume.LITERS_450: RX = 450.0;break;
                    case BathVolume.LITERS_550: RX = 550.0;break;
                }
            }
            else {
                switch (person.waterBathVolume) {
                    case BathVolume.LITERS_50:  RX = 37.8;break;
                    case BathVolume.LITERS_100: RX = 94.6;break;
                    case BathVolume.LITERS_150: RX = 151.4;break;
                    case BathVolume.LITERS_200: RX = 208.2;break;
                    case BathVolume.LITERS_250: RX = 264.9;break;
                    case BathVolume.LITERS_300: RX = 321.7;break;
                    case BathVolume.LITERS_350: RX = 378.0;break;
                    case BathVolume.LITERS_400: RX = 425.3;break;
                    case BathVolume.LITERS_450: RX = 492.0;break;
                    case BathVolume.LITERS_550: RX = 567.8;break;
                }
            }


            RX = RX * person.bathNumber / 7.0; // liczba kąpieli dziennie
            RX = RX + 50.0 * person.showerNumber / 7.0 + 5;

            var avgTemp:Number = new Number(0);
            for(var i:int = 0;i < 12;i++){
                avgTemp += chosenCountry.getMonthTemperature(i)/12;
            }

            var coalHeatGJPrimary:Number = 0;
            var oilHeatGJPrimary:Number = 0;
            var gasHeatGJPrimary:Number = 0;
            var biomassHeatGJPrimary:Number = 0;
            var electricityGJPrimary:Number = 0;

            var tempDiff:Number = 38 - Math.max(avgTemp,4) ;
            var warmWaterEnergyGJ:Number = ((4190 * RX * tempDiff) * 365)/(1000 * 1000 * 1000);

            EW = 1.00;
            if (person.waterHeatingSystem == HouseHeatingSource.CENTRAL) {
                if (!params.nonStatisticMode) // w trybie statystycznym dla ludności
                {
                    EW = 0.9 * params.heatGJCO2Coefficient / Coefficients.GAS_HEAT_GJ;   // Trudności z pozyskaniem informacji DH (Distant Heating) i CHP (Combined Heat and Power)
                    electricityGJPrimary = 0.9 * RX;
                }
                else {
                    EW = 0.2 * params.heatGJCO2Coefficient / Coefficients.GAS_HEAT_GJ;   // Centralne ogrzewanie - sieć miejska (80% redukcja emisji przy kogeneracji)
                    electricityGJPrimary = 0.2 * RX;
                }
            }
            else {
                switch (person.waterHeatingSystem) {
                    case HouseHeatingSource.OIL:
                        oilHeatGJPrimary = getFossilHeatEnergyAmountForWater(RX, person.heatingRenewableRatio) * Coefficients.PRIMARY_FINAL_OIL_EN_RATIO;
                        EW = 1.15;
                        break;
                    case HouseHeatingSource.GAS:
                        EW = 1.0;
                        gasHeatGJPrimary = getFossilHeatEnergyAmountForWater(RX,person.heatingRenewableRatio) * Coefficients.PRIMARY_FINAL_GAS_AVERAGE_EN_RATIO;
                        break;
                    case HouseHeatingSource.COAL_OLD:
                        EW = 3.2;
                        coalHeatGJPrimary = getFossilHeatEnergyAmountForWater(RX, person.heatingRenewableRatio) * Coefficients.PRIMARY_FINAL_COAL_FURNACE_EN_RATIO;
                        break;
                    case HouseHeatingSource.COAL_MODERN:
                        EW = 2.0;
                        coalHeatGJPrimary = getFossilHeatEnergyAmountForWater(RX, person.heatingRenewableRatio) * Coefficients.PRIMARY_FINAL_COAL_MODERN_EN_RATIO;
                        break;
                    case HouseHeatingSource.ELECTRIC:
                        EW = params.electricityGJCO2Coefficient / Coefficients.GAS_ELECTRICITY_GJ;
                        electricityGJPrimary = getFossilHeatEnergyAmountForWater(RX, person.heatingRenewableRatio);
                        break;
                    case HouseHeatingSource.BIOMASS:
                        EW = 0.1;
                        biomassHeatGJPrimary = getFossilHeatEnergyAmountForWater(RX,person.heatingRenewableRatio)
                                * Coefficients.PRIMARY_FINAL_BIOMASS_EN_RATIO;
                        break;
                }
            }

            calcResult.coalEnergy += coalHeatGJPrimary;
            calcResult.oilEnergy += oilHeatGJPrimary;
            calcResult.gasEnergy += gasHeatGJPrimary;
            calcResult.biomassEnergy += biomassHeatGJPrimary;
            calcResult.electricityEnergy += electricityGJPrimary;

            calcResult.hotWaterEnergy.coalEnergy += coalHeatGJPrimary;
            calcResult.hotWaterEnergy.oilEnergy += oilHeatGJPrimary;
            calcResult.hotWaterEnergy.gasEnergy += gasHeatGJPrimary;
            calcResult.hotWaterEnergy.biomassEnergy += biomassHeatGJPrimary;
            calcResult.hotWaterEnergy.electricityEnergy += electricityGJPrimary;

            RX = RX * 0.0055 * EW; // Przelicz litry na tony CO2 rocznie
            calcResult.hotWater = RX;
        }
        return calcResult;
    }

    /**********************************Mieszkanie*****************************************/

    private function calculateHome(calcResult:CalculationResult,person:Person, chosenCountry:Country,params:CalculationParams):CalculationResult {
        var RX:Number = new Number(0);
        var RE:Number = new Number(0);

        var energyCoefficient:Number = new Number(0);
        var energyInsulation:Number = new Number(0);
        var perPersonElectricityUsage:Number = new Number(0);
        var livingArea:Number = new Number(0);
        var houseHolderCount:Number = new Number(0);
        var acCoefficient:Number = new Number(0);
        var corrEC100:Number = new Number(0);
        var emissionCO2PerGJ:Number = new Number(0);
        var heatingIntensityRef:Number = new Number(0);
        var coolingIntensityRef:Number = new Number(0);
        var houseType:Number = new Number(0);
        var houseInsulation:Number = new Number(0);
        var ventilationEff:Number = new Number(0);
        var i:int = new int(0);
        var buff:Number = new Number(0);
        var tempRef:Number = new Number(0);


        if ((person.houseType != -1) && (person.insulation != -1) && (person.buildingMaterial != -1) &&
                (person.heatingTemperature != -1) && (person.ventilationMethod != -1) && (person.heatingSource != -1)) {
            livingArea = person.livingArea;
            if (params.units != 'M') {
                livingArea = livingArea * 0.09290304; // Przeliczenie ze stóp na metry (kwadratowe 0.3048*0.3048)
            }
            houseHolderCount = person.personNumber;
            houseType = person.houseType;
            houseInsulation = person.insulation;

            energyInsulation = 150;

            if (houseInsulation == HouseInsulation.VERY_POOR) {
                switch (houseType) {
                    case HouseType.DETACHED: energyInsulation = 310;break; // Wolnostojący nieocieplony
                    case HouseType.TERRACE: energyInsulation = 270;break; // Blok nieocieplony
                    case HouseType.MULTI_FAMILY: energyInsulation = 230;break; // Wolnostojący słabo ocieplony
                }
            }
            else if (houseInsulation == HouseInsulation.POOR) { //słabo ocieplony
                switch (houseType) {
                    case HouseType.DETACHED: energyInsulation = 230;break;
                    case HouseType.TERRACE: energyInsulation = 200;break;
                    case HouseType.MULTI_FAMILY: energyInsulation = 170;break;
                }
            }
            else if (houseInsulation == HouseInsulation.MEDIUM) {  //srednio ocieplony
                switch (houseType) {
                    case HouseType.DETACHED: energyInsulation = 170;break;
                    case HouseType.TERRACE: energyInsulation = 150;break;
                    case HouseType.MULTI_FAMILY: energyInsulation = 130;break;
                }
            }
            else if (houseInsulation == HouseInsulation.GOOD) {   //dobrze ocieplony
                switch (houseType) {
                    case HouseType.DETACHED: energyInsulation = 130;break;
                    case HouseType.TERRACE: energyInsulation = 115;break;
                    case HouseType.MULTI_FAMILY: energyInsulation = 100;break;
                }
            }
            else if (houseInsulation == HouseInsulation.EXCELLENT) {   //doskonale ocieplony
                switch (houseType) {
                    case HouseType.DETACHED: energyInsulation = 100;break;
                    case HouseType.TERRACE: energyInsulation = 90;break;
                    case HouseType.MULTI_FAMILY: energyInsulation = 90;break;
                }
            }
            else if (houseInsulation == HouseInsulation.PASSIVE) { //pasywny?
                switch (houseType) {
                    case HouseType.DETACHED: energyInsulation = 80;break;
                    case HouseType.TERRACE: energyInsulation = 70;break;
                    case HouseType.MULTI_FAMILY: energyInsulation = 70;break;
                }
            }

            energyCoefficient = energyInsulation / 1000.0; // kWh->MWh [y]
            energyCoefficient = energyCoefficient * livingArea; // energia sumaryczna

            // Sposób wietrzenia
            ventilationEff = 1.00;
            switch (person.ventilationMethod) {
                case HouseVentilation.FAST: ventilationEff = 0.7;break;
                case HouseVentilation.LONG: ventilationEff = 1.5;break;
            }

            energyCoefficient = energyCoefficient * ventilationEff;
            perPersonElectricityUsage = getElectricityYearMWh(person);

            var houseTemperature:int = new int(0);

            if (params.units == 'M') {
                switch (person.heatingTemperature) {
                    case HouseHeating.VERY_LOW: houseTemperature = 17;break;
                    case HouseHeating.LOW: houseTemperature = 19;break;
                    case HouseHeating.AVERAGE: houseTemperature = 21;break;
                    case HouseHeating.HIGH: houseTemperature = 23;break;
                    case HouseHeating.VERY_HIGH: houseTemperature = 25;break;
                }
            }
            else {
                switch (person.heatingTemperature) {
                    case HouseHeating.VERY_LOW: houseTemperature = 16;break;
                    case HouseHeating.LOW: houseTemperature = 18;break;
                    case HouseHeating.AVERAGE: houseTemperature = 21;break;
                    case HouseHeating.HIGH: houseTemperature = 23;break;
                    case HouseHeating.VERY_HIGH: houseTemperature = 25;break;
                }
            }

            var heatingIntensity:Number = 1;
            heatingIntensityRef = 1;

            for (i = 0; i < 12; i++) {
                tempRef = chosenCountry.getMonthTemperature(i) - (houseTemperature - 21);
                heatingIntensity = heatingIntensity + refData.getHeatingIntensityForTemp(tempRef);
                heatingIntensityRef = heatingIntensityRef + refData.getHeatingIntensityForTemp(refData.getUKTempRefForMonth(i + 1));
            }

            energyCoefficient = energyCoefficient * heatingIntensity / heatingIntensityRef;
            corrEC100 = 0.0;

            for (i = 0; i < 12; i++) {
                var temperature:int = chosenCountry.getMonthTemperature(i) - (houseTemperature - 21);
                RX = energyCoefficient * refData.getHeatingIntensityForTemp(temperature) / heatingIntensity;
                if (RX > perPersonElectricityUsage / 12) {
                    RX = RX - perPersonElectricityUsage / 12;
                }
                corrEC100 = corrEC100 + RX;
            }

            energyCoefficient = 3.6 * corrEC100; // MWh->GJ

            var coalHeatGJPrimary:Number = 0;
            var oilHeatGJPrimary:Number = 0;
            var gasHeatGJPrimary:Number = 0;
            var biomassHeatGJPrimary:Number = 0;
            var electricityGJPrimary:Number = 0;

            // Emisja CO2 na 1GJ
            emissionCO2PerGJ = 1.00;
            var coalHeatGJ:Number = Coefficients.COAL_HEAT_GJ;
            if(chosenCountry.nameEn == 'Estonia'){
                coalHeatGJ = coalHeatGJ * 1.4;
            }
            switch (person.heatingSource) {
                case HouseHeatingSource.CENTRAL:
                {
                    if (!params.nonStatisticMode) {
                        emissionCO2PerGJ = 0.9 * params.heatGJCO2Coefficient; // w trybie statystycznym dla ludności Trudności z pozyskaniem informacji DH (Distant Heating) i CHP (Combined Heat and Power)
                        electricityGJPrimary = 0.9 * energyCoefficient/houseHolderCount;
                    }
                    else {
                        emissionCO2PerGJ = 0.2 * params.heatGJCO2Coefficient; // Centralne ogrzewanie - sieć miejska (80% redukcja emisji przy kogeneracji)
                        electricityGJPrimary = 0.2 * energyCoefficient/houseHolderCount;
                    }
                    break;
                }
                case HouseHeatingSource.OIL:
                    emissionCO2PerGJ = Coefficients.OIL_HEAT_GJ;
                    oilHeatGJPrimary = getFossilHeatEnergyAmount(energyCoefficient,houseHolderCount,person.heatingRenewableRatio) *
                            Coefficients.PRIMARY_FINAL_OIL_EN_RATIO;
                    break;
                case HouseHeatingSource.GAS:
                    emissionCO2PerGJ = Coefficients.GAS_HEAT_GJ;
                    gasHeatGJPrimary = getFossilHeatEnergyAmount(energyCoefficient,houseHolderCount,person.heatingRenewableRatio) *
                            Coefficients.PRIMARY_FINAL_GAS_AVERAGE_EN_RATIO;
                    break;
                case HouseHeatingSource.COAL_OLD:
                    coalHeatGJPrimary = getFossilHeatEnergyAmount(energyCoefficient,houseHolderCount,person.heatingRenewableRatio) * Coefficients.PRIMARY_FINAL_COAL_FURNACE_EN_RATIO;
                    emissionCO2PerGJ = coalHeatGJ * 1.6;
                    break;
                case HouseHeatingSource.COAL_MODERN:
                    coalHeatGJPrimary = getFossilHeatEnergyAmount(energyCoefficient,houseHolderCount,person.heatingRenewableRatio) * Coefficients.PRIMARY_FINAL_COAL_MODERN_EN_RATIO;
                    emissionCO2PerGJ = coalHeatGJ;
                    break;
                case HouseHeatingSource.ELECTRIC:
                    electricityGJPrimary = getFossilHeatEnergyAmount(energyCoefficient,houseHolderCount,person.heatingRenewableRatio);
                    emissionCO2PerGJ = params.electricityGJCO2Coefficient;
                    break;
                case HouseHeatingSource.BIOMASS:
                    biomassHeatGJPrimary = getFossilHeatEnergyAmount(energyCoefficient,houseHolderCount,person.heatingRenewableRatio)
                            * Coefficients.PRIMARY_FINAL_BIOMASS_EN_RATIO;
                    emissionCO2PerGJ = Coefficients.GAS_HEAT_GJ * 0.1;
                    break;
            }


            calcResult.coalEnergy += coalHeatGJPrimary;
            calcResult.oilEnergy += oilHeatGJPrimary;
            calcResult.gasEnergy += gasHeatGJPrimary;
            calcResult.biomassEnergy += biomassHeatGJPrimary;
            calcResult.electricityEnergy += electricityGJPrimary;

            calcResult.heatingEnergy.coalEnergy += coalHeatGJPrimary;
            calcResult.heatingEnergy.oilEnergy += oilHeatGJPrimary;
            calcResult.heatingEnergy.gasEnergy += gasHeatGJPrimary;
            calcResult.heatingEnergy.biomassEnergy += biomassHeatGJPrimary;
            calcResult.heatingEnergy.electricityEnergy += electricityGJPrimary;



            //Wynik = Wartość [2]*mnożnik [3] / liczba osób [4] * Efektywność (+Temperatura)*(100-odnawialne)
            RX = energyCoefficient / houseHolderCount * (0.15 + 0.85 * (100.0 - person.heatingRenewableRatio) / 100.0) * emissionCO2PerGJ;
            RX = RX / 1000.0; // kg CO2->Tony CO2

            calcResult.heating = RX;

            RE = RE + RX;
            // Energia od chłodzenia (klimatyzacji)


            var airConditioning:Number = 0;
            if (person.acEnabled) {
                if (person.acFrequency != -1 && person.acDuration != -1 && person.acTemp != -1) {
                    acCoefficient = 1.0;
                    switch (person.acFrequency) {
                        case AcFrequency.EXCEPTIONALLY: acCoefficient = 0.50;break;
                        case AcFrequency.RARELY: acCoefficient = 0.70;break;
                        case AcFrequency.USUALLY: acCoefficient = 1.50;break;
                    }

                    switch (person.acDuration) {
                        case AcDuration.NIGHTS: acCoefficient = acCoefficient * 0.50;break;
                        case AcDuration.NIGHTS_AND_WEEKENDS: acCoefficient = acCoefficient * 1.00;break;
                        case AcDuration.ALWAYS: acCoefficient = acCoefficient * 1.70;break;
                    }

                    //Wynik = Wartość [2]*mnożnik [3] / liczba osób [4] * Efektywność (+Temperatura)*(100-odnawialne)
                    energyCoefficient = 150.0 * acCoefficient * livingArea; // Współczynnik 1 (energia na ogrzewanie vs. średnie użycie klimy w Singapurze 235kWH/m2/y * 64%)
                    energyCoefficient = energyCoefficient / 1000.0; // kWh->MWh
                    energyCoefficient = energyCoefficient * energyInsulation / 130.0;

                    var coolingTemp:int = 0;

                    switch (person.acTemp) {
                        case AcTemp.VERY_LOW:
                            coolingTemp = 21;
                            break;
                        case AcTemp.LOW:
                            coolingTemp = 23;
                            break;
                        case AcTemp.AVERAGE:
                            coolingTemp = 25;
                            break;
                        case AcTemp.HIGH:
                            coolingTemp = 27;
                            break;
                        case AcTemp.VERY_HIGH:
                            coolingTemp = 29;
                            break;
                    }

                    var coolingIntensity:Number = 1;
                    coolingIntensityRef = 1;
                    for (i = 0; i < 12; i++) {
                        tempRef = chosenCountry.getMonthTemperature(i) - (coolingTemp - 25);
                        var toAdd:Number = refData.getCoolingSForTemp(tempRef);
                        coolingIntensity = coolingIntensity + toAdd;
                        var TCRefValue:Number = refData.getSingaporeTempRef(i + 1);
                        coolingIntensityRef = coolingIntensityRef + refData.getCoolingSForTemp(TCRefValue);
                    }

                    energyCoefficient = energyCoefficient * coolingIntensity / coolingIntensityRef;
                    corrEC100 = 0.0;

                    for (i = 0; i < 12; i++) {
                        tempRef = chosenCountry.getMonthTemperature(i) - (coolingTemp - 25);
                        RX = energyCoefficient * refData.getCoolingSForTemp(tempRef) / coolingIntensity;
                        //          if RX>EEl/12 then
                        RX = RX + 1.2 * perPersonElectricityUsage / 12;
                        corrEC100 = corrEC100 + RX;
                    }

                    energyCoefficient = 3.6 * corrEC100; // MWh->GJ

                    var acEnergy:Number = (energyCoefficient / houseHolderCount) * (0.15 + 0.85 * (100.0 - person.renewableRatio) / 100.0);
                    calcResult.airConditioningEnergy.electricityEnergy += acEnergy;

                    calcResult.electricityEnergy += acEnergy;
                    RX = energyCoefficient / houseHolderCount * params.electricityGJCO2Coefficient * (0.15 + 0.85 * (100.0 - person.renewableRatio) / 100.0);
                    RX = RX / 1000.0; // kg CO2->Tony CO2

                    if (!params.nonStatisticMode) {
                        // w trybie statystycznym dla ludności
                        RX = RX / 2.5; // Korekta na rozpowszechnienie klimy
                    }
                    airConditioning = RX;
                }
            }

            calcResult.airConditioning = airConditioning;

            var floorArea:Number;
            var internalWalls:Number;
            var externalWalls:Number;
            var roofArea:Number;

            floorArea = livingArea;

            // Zużycie energii na wybudowanie domu
            RX = 0.0;
            switch (person.houseType) {
                case HouseType.DETACHED:
                    roofArea = 2 * livingArea / 3;
                    externalWalls = 4* Math.sqrt(livingArea/2) * 6;
                    internalWalls = externalWalls;
                    RX = (0.20 + 0.54 * livingArea / 100) / houseHolderCount;
                    break;
                case HouseType.TERRACE:
                    roofArea = 2 * livingArea / 3;
                    externalWalls = 2.6* Math.sqrt(livingArea/2) * 6;
                    internalWalls = 1.4* Math.sqrt(livingArea/2) * 6 + 0.7 * floorArea;
                    RX = (0.18 + 0.40 * livingArea / 100) / houseHolderCount;
                    break;
                case HouseType.MULTI_FAMILY:
                    roofArea =  livingArea * 0.25;
                    externalWalls = 2* Math.sqrt(livingArea) * 3;
                    internalWalls = Math.sqrt(livingArea) * 3 + 0.7 * floorArea;
                    RX = (0.18 + 0.40 * livingArea / 100) / houseHolderCount;
                    RX = (0.16 + 0.27 * livingArea / 100) / houseHolderCount;
                    break;
            }
            switch (person.insulation) {
                case HouseInsulation.VERY_POOR:
                    RX = RX * 0.80;
                    break;
                case HouseInsulation.POOR:
                    RX = RX * 0.90;
                    break;
                case HouseInsulation.MEDIUM:
                    RX = RX * 1.00;
                    break;
                case HouseInsulation.GOOD:
                    RX = RX * 1.12;
                    break;
                case HouseInsulation.EXCELLENT:
                    RX = RX * 1.30;
                    break;
                //passive?
            }


            var buildingEnergy:Number = (floorArea * Coefficients.FLOOR_GJ_PER_SQUARE_METER +
                    roofArea * Coefficients.ROOF_GJ_PER_SQUARE_METER +
                    externalWalls * Coefficients.EXTERNAL_WALLS_GJ_PER_SQUARE_METER +
                    internalWalls * Coefficients.INTERNAL_WALLS_GJ_PER_SQUARE_METER)/(100 * houseHolderCount);


            switch (person.buildingMaterial) {
                case HouseMaterial.BRICK:
                    RX = RX * 0.8;
                    break;
                case HouseMaterial.WOOD:
                    RX = RX * 0.2;
                    buildingEnergy = buildingEnergy * 0.25;
                    break;
                case HouseMaterial.CONCRETE:
                    buildingEnergy = buildingEnergy * 1.2;
                    break;
            }


            calcResult.electricityEnergy += buildingEnergy;
            calcResult.constructionMaintenanceEnergy.electricityEnergy += buildingEnergy;

            RX = RX * (0.3 * person.transportEmissionReduction + 0.4 * person.industrialEmissionReduction + 0.2 * params.electricityGJCO2Coefficient / Coefficients.GAS_ELECTRICITY_GJ);
            calcResult.constructionMaintenance = RX;
        }
        //return RE;
        return calcResult;
    }

    private function getFossilHeatEnergyAmount(energyCoefficient:Number,houseHolderCount:Number,renewableRatio:Number):Number {
        return energyCoefficient / houseHolderCount * (0.15 + 0.85 * (100.0 - renewableRatio) / 100.0)
    }

    private function getFossilHeatEnergyAmountForWater(energyCoefficient:Number,renewableRatio:Number):Number {
        return energyCoefficient  * (0.15 + 0.85 * (100.0 - renewableRatio) / 100.0)
    }

    public function consLevel2CO2(Consumption:Number, RichCoeff:Number):Number {
        return 0.625 * (Math.log((Consumption * RichCoeff + 1500) / 100) - 2.7);
        //  Result:=0.680*(ln((CVCX*RichC+1500)/100)-2.7);
    }

    public function setCoefficientCalculator(value:CoefficientCalculator):void {
        coefficientCalculator = value;
    }
}
}



 
 
 
 
 
 
 